//
let express = require('express');
let app = express();
let path = require('path');
let fse = require('fs-extra');
let nunjucks = require('nunjucks');
let bodyParser = require('body-parser');
let session = require('express-session');
// let multer = require('multer');
let morgan = require('morgan');

/* 日志 */
app.use(morgan('dev', {}));
// 保存日志
let logDIR = path.join(__dirname, 'logs/access.log');
fse.ensureFile(logDIR).then(() => {
  app.use(morgan('common', {
    stream: fse.createWriteStream(logDIR, {flags: 'a'})
  }));
});
// post 请求内容处理中间件
app.use(bodyParser.urlencoded({
  extended: true
}));// for parsing application/x-www-form-urlencoded
app.use(bodyParser.json());// for parsing application/json
// 最好不要全局使用
// app.use(multer()); // for parsing multipart/form-data

// 使用 session 中间件
app.use(session({
  // 对session id 相关的cookie 进行签名
  secret: 'giadmin',
  // 这里的name值得是传递sessionid的cookie的name，默认是：connect.sid
  name: 'giadminsid',
  resave: true,// 每次请求都会再设置为失效时间
  saveUninitialized: true, // 是否保存未初始化的会话
  cookie: {
    maxAge : 1000 * 60 * 60, // 设置 session 的有效时间，单位毫秒
  },
}));

// 模板系统
nunjucks.configure('views', {
  autoescape: true,
  express: app
});

/* 全局加载启动 */
require('./editor-controller/bootstrap.js');
global.editorPath = '/editor-ui';
global.editorPreviewPath = '/preview';
global.upStyleTagsFileName = "styleTags.txt";

// 注册定时器
require('./bootstrap/backups');

// 开发环境
if(process.env.NODE_ENV === 'development'){
  // 编辑器静态资源路径，/editor-ui
  app.use(global.editorPath, express.static('editor-ui'));
  // 发布显示
  app.use('/view', express.static('./publish'));
}

// static
app.use(express.static('static'));

// 不需要验证登陆的地址
let notAuthorizationRouters = ['/login', '/log-in', global.editorPreviewPath];

/* 填入完整的url */
app.use('*', (req, res, next) => {
  let ret_msg = '';
  req.fullURL = `${req.protocol}://${req.get('host')}${global.editorPreviewPath}/`;
  // 图示消息传递
  if(typeof req.session.messages === 'string'){
    ret_msg = {
      type: 'info',
      msg: req.session.messages
    };
  } else {
    ret_msg = req.session.messages;
  }
  res.locals.messages = ret_msg;
  // 重置清空消息
  req.session.messages = undefined;
  // 需要验证请求
  if(notAuthorizationRouters.indexOf(req.baseUrl) < 0) {
    let userinfo = req.session.userinfo;
    if(!userinfo){
      res.redirect('/login');
      return;
    }
  }
  next();
});

// manage client view
app.use('/', require('./routes'));

// server api
app.use('/api', require('./routes/api'));

// ueditor api controller
app.use('/editorapi', require('./editor-controller'));

// no find uri
app.use('*', (req, res) => {
  res.status(404).json({
    status: false,
    code: 404,
    data: req.url,
    msg: '未注册的服务'
  });
});

// 开启服务
let port = 3001;
app.listen(port, () => {
  console.log(`Server Listen：http://127.0.0.1:${port}/`);
});

// module.exports = app;
